module.exports = class extends think.Model {
  
  /**
   * 菜单生成辅助函数
   * @param menuItem
   * @param parent_id
   * @param appid
   * @returns {Promise<void>}
   * @private
   */
  async _makeMenuItem(menuItem, parent_id = 0, appid = '') {
    if (menuItem.hasOwnProperty('name') && menuItem.hasOwnProperty('path')) {
      
      menuItem.parent_id = parent_id;
      menuItem.appid = appid;
      //think.logger.debug(menuItem);
      let id = await this.add(menuItem);
      if (menuItem.hasOwnProperty('children')) {
        for (let m of menuItem.children) {
          await this._makeMenuItem(m, id, appid);
        }
      }
    }
  }
  
  /**
   * 生成系统菜单
   * @param menus
   * @param appid
   * @returns {Promise<void>}
   */
  async makeMenus(menus, appid = 'framework') {
    this.where(true).delete();
    for (let m of menus) {
      await this._makeMenuItem(m, 0, appid);
    }
  }
  
  async _getMenuItem(menus, m, parent_id, appid) {
  
    delete (m.id);
    delete (m.appid);
    delete (m.parent_id);
    
    let children = await this.where({appid: appid, parent_id: parent_id}).select();
    if (!think.isEmpty(children)) {
      m.children = children;
    }
    //m.children = children;
    
    if (!think.isEmpty(children)) {
      for (let menu of children) {
        const menu_id = menu.id;
         this._getMenuItem(menus, menu, menu_id, appid);
      }
    }
  }
  
  async getMenus(appid = 'framework') {
    let menus = [];
    let top_level_menus = await this.where({appid: appid, parent_id: 0}).select();
    think.logger.debug("top_level_menus:",top_level_menus);
    for (let m of top_level_menus) {
      const parent_id = m.id;
      menus.push(m)
      await this._getMenuItem(menus, m, parent_id, appid);
    }
    //think.logger.debug(menus);
    return menus;
    
  }
  
};
